<template>
  <a-tabs v-model:activeKey="activeKey" class="plant-add">
    <a-tab-pane key="1" tab="信息">
      <a-form v-if="optionTotal" class="form-container" ref="formRef" :label-col="{ style: { width: '160px' } }"
              :model="formState">
        <a-form-item label="编号" name="number" :rules="[{ required: true, message: '请输入编号' }]">
          <a-input v-model:value="formState.number" placeholder="请输入编号" />
        </a-form-item>
        <a-form-item label="植物名" name="chinese_name" :rules="[{ required: true, message: '请输入植物名' }]">
          <a-input v-model:value="formState.chinese_name" placeholder="请输入植物名" />
        </a-form-item>
        <a-form-item label="拉丁学名" name="latin_name" :rules="[{ required: true, message: '请输入拉丁学名' }]">
          <a-input v-model:value="formState.latin_name" placeholder="请输入拉丁学名" />
        </a-form-item>
        <a-form-item label="别名" name="alias" :rules="[{ required: true, message: '请输入别名' }]">
          <a-input v-model:value="formState.alias" placeholder="请输入别名" />
        </a-form-item>
        <a-form-item label="药材名" name="medicinal_name" :rules="[{ required: true, message: '请输入药材名' }]">
          <a-input v-model:value="formState.medicinal_name" placeholder="请输入药材名" />
        </a-form-item>
        <a-form-item label="植物识别基础关键词" name="identify_key_words"
                     :rules="[{ required: true, message: '请选择植物识别基础关键词' }]">
          <a-select v-model:value="formState.identify_key_words" mode="multiple" showArrow
                    placeholder="请选择植物识别基础关键词">
            <a-select-option v-for="item in optionTotal.plant_recognition_class" :key="item" :value="item">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="文字描述" name="describe_info" :rules="[{ required: true, message: '请输入文字描述' }]">
          <a-textarea v-model:value="formState.describe_info" placeholder="请输入文字描述" :rows="5" />
        </a-form-item>
        <a-form-item label="花期和果期" name="flowering_and_fruiting"
                     :rules="[{ required: true, message: '请输入花期和果期' }]">
          <a-input v-model:value="formState.flowering_and_fruiting" placeholder="请输入花期和果期" />
        </a-form-item>
        <!-- <a-form-item label="地理分布" name="geographical"
                     :rules="[{ required: true, message: '请选择地理分布' }]">
          <a-select v-model:value="formState.geographical" mode="multiple" showArrow placeholder="请选择地理分布">
            <a-select-option v-for="item in optionTotal.provinces_class" :key="item" :value="item">
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="生境" name="living_environment" :rules="[{ required: true, message: '请输入生境' }]">
          <a-input v-model:value="formState.living_environment" placeholder="请输入生境" />
        </a-form-item>
        <a-form-item label="应用部位" name="medicinal_parts"
                     :rules="[{ required: true, message: '请选择应用部位' }]">
          <a-checkbox-group v-model:value="formState.medicinal_parts" :options="optionTotal.plant_parts" />
        </a-form-item>
        <a-form-item label="传统功效" name="traditional_efficacy_class"
                     :rules="[{ required: true, message: '请选择传统功效' }]"
        >
          <a-checkbox-group v-model:value="formState.traditional_efficacy_class"
                            :options="optionTotal.traditional_efficacy_class"
          />
        </a-form-item>
        <a-form-item label="功效" name="effect"
                     :rules="[{ required: true, message: '请选择功效' }]"
        >
          <a-checkbox-group v-model:value="formState.effect"
                            :options="['清热药','抗疟，消热','清热燥湿，泻火解毒','祛风杀虫，通经止痛', '解毒，除湿，通利关节']"
          />
        </a-form-item>
        <a-form-item label="军事医学应用分类" name="military_medical_class"
                     :rules="[{ required: true, message: '请选择军事医学应用分类' }]"
        >
          <a-checkbox-group v-model:value="formState.military_medical_class"
                            :options="optionTotal.military_medical_class"
          />
        </a-form-item>
        <a-form-item label="疾病分类" name="disease_name_class"
                     :rules="[{ required: true, message: '请选择疾病分类' }]"
        >
          <a-checkbox-group v-model:value="formState.disease_name_class"
                            :options="optionTotal.disease_name_class"
          />
        </a-form-item>
        <a-form-item label="适应症/用法" name="indication_usage"
                     :rules="[{ required: true, message: '请输入适应症/用法' }]">
          <a-textarea v-model:value="formState.indication_usage" placeholder="请输入适应症/用法" :rows="5" />
        </a-form-item>
        <!-- <a-form-item label="军事应用分类" name="types_of_military_applications"
                     :rules="[{ required: true, message: '请选择军事应用分类' }]"
        >
          <a-checkbox-group v-model:value="formState.types_of_military_applications"
                            :options="optionTotal.use"
          />
        </a-form-item> -->
        <!--    自定义字段的其他    -->
        <a-form-item v-if="false" label="其他" name="medicinal_field_list">
          <div v-if="formState.medicinal_field_list && formState.medicinal_field_list.length">
            <a-form-item v-for="(item, index) in formState.medicinal_field_list" :key="index">
              <a-input-group compact>
                <a-input v-model:value="item.field_name" placeholder="请输入字段名" style="width: 30%" />
                <a-input v-model:value="item.field_content" placeholder="请输入对应内容" style="width: 54.5%" />
                <a-button type="primary" danger @click="delOther(index)">
                  <MinusOutlined />
                </a-button>
                <a-button type="primary" @click="addOther">
                  <PlusOutlined />
                </a-button>
              </a-input-group>
            </a-form-item>
          </div>
          <a-button v-else type="primary" @click="addOther">添加</a-button>
        </a-form-item>
        <!--    文本的其他    -->
        <a-form-item v-else label="其他" name="other">
          <a-textarea v-model:value="formState.other" placeholder="请输入其他" :rows="5" />
        </a-form-item>
      </a-form>
      <div style="text-align: center">
        <a-button type="primary" @click="nextStep">下一步</a-button>
      </div>
    </a-tab-pane>
    <a-tab-pane key="2" tab="图片">
      <a-card title="手绘图">
        <a-upload
          v-model:file-list="formState.hand_painted_url"
          :data="{ plant_number: formState.number, image_type: 0 }"
          :action="actionUrl"
          accept=".jpg, .png, .jpeg"
          list-type="picture-card"
          @preview="handlePreview"
        >
          <div v-if="fileList.length < 8">
            <plus-outlined />
            <div style="margin-top: 8px">点击上传</div>
          </div>
        </a-upload>
        <div>只能上传jpg/png文件，且不超过500kb</div>
      </a-card>
      <div class="upload-line">
        <a-card title="生境">
          <a-upload
            v-model:file-list="formState.living_url"
            :data="{ plant_number: formState.number, image_type: 1 }"
            :action="actionUrl"
            accept=".jpg, .png, .jpeg"
            list-type="picture-card"
            @preview="handlePreview"
          >
            <div v-if="fileList.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">点击上传</div>
            </div>
          </a-upload>
          <div>只能上传jpg/png文件，且不超过500kb</div>
        </a-card>
        <a-card title="全株">
          <a-upload
            v-model:file-list="formState.whole_plant_url"
            :data="{ plant_number: formState.number, image_type: 2 }"
            :action="actionUrl"
            accept=".jpg, .png, .jpeg"
            list-type="picture-card"
            @preview="handlePreview"
          >
            <div v-if="fileList.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">点击上传</div>
            </div>
          </a-upload>
          <div>只能上传jpg/png文件，且不超过500kb</div>
        </a-card>
      </div>
      <div class="upload-line">
        <a-card title="根">
          <a-upload
            v-model:file-list="formState.root_url"
            :data="{ plant_number: formState.number, image_type: 3 }"
            :action="actionUrl"
            accept=".jpg, .png, .jpeg"
            list-type="picture-card"
            @preview="handlePreview"
          >
            <div v-if="fileList.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">点击上传</div>
            </div>
          </a-upload>
          <div>只能上传jpg/png文件，且不超过500kb</div>
        </a-card>
        <a-card title="茎">
          <a-upload
            v-model:file-list="formState.stem_url"
            :data="{ plant_number: formState.number, image_type: 4 }"
            :action="actionUrl"
            accept=".jpg, .png, .jpeg"
            list-type="picture-card"
            @preview="handlePreview"
          >
            <div v-if="fileList.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">点击上传</div>
            </div>
          </a-upload>
          <div>只能上传jpg/png文件，且不超过500kb</div>
        </a-card>
      </div>
      <div class="upload-line">
        <a-card title="叶">
          <a-upload
            v-model:file-list="formState.leaf_url"
            :data="{ plant_number: formState.number, image_type: 5 }"
            :action="actionUrl"
            accept=".jpg, .png, .jpeg"
            list-type="picture-card"
            @preview="handlePreview"
          >
            <div v-if="fileList.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">点击上传</div>
            </div>
          </a-upload>
          <div>只能上传jpg/png文件，且不超过500kb</div>
        </a-card>
        <a-card title="花">
          <a-upload
            v-model:file-list="formState.flower_url"
            :data="{ plant_number: formState.number, image_type: 6 }"
            :action="actionUrl"
            accept=".jpg, .png, .jpeg"
            list-type="picture-card"
            @preview="handlePreview"
          >
            <div v-if="fileList.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">点击上传</div>
            </div>
          </a-upload>
          <div>只能上传jpg/png文件，且不超过500kb</div>
        </a-card>
      </div>
      <div class="upload-line">
        <a-card title="果实">
          <a-upload
            v-model:file-list="formState.fruit_url"
            :data="{ plant_number: formState.number, image_type: 7 }"
            :action="actionUrl"
            accept=".jpg, .png, .jpeg"
            list-type="picture-card"
            @preview="handlePreview"
          >
            <div v-if="fileList.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">点击上传</div>
            </div>
          </a-upload>
          <div>只能上传jpg/png文件，且不超过500kb</div>
        </a-card>
        <a-card title="种子">
          <a-upload
            v-model:file-list="formState.seed_url"
            :data="{ plant_number: formState.number, image_type: 8 }"
            :action="actionUrl"
            accept=".jpg, .png, .jpeg"
            list-type="picture-card"
            @preview="handlePreview"
          >
            <div v-if="fileList.length < 8">
              <plus-outlined />
              <div style="margin-top: 8px">点击上传</div>
            </div>
          </a-upload>
          <div>只能上传jpg/png文件，且不超过500kb</div>
        </a-card>
      </div>
      <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
        <img alt="example" style="width: 100%" :src="previewImage" />
      </a-modal>
      <div style="text-align: center; margin-top: 24px;">
        <a-button type="primary" @click="save">保存</a-button>
      </div>
    </a-tab-pane>
  </a-tabs>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { MinusOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import { fetchOptionList } from '@/api/common'
import { fetchPlantDetail, fetchPlantInsertOne, fetchPlantUpdate } from '@/api/plant'


const router = useRouter()
const route = useRoute()

const id = ref()
// @ApiModelProperty(value = "植物区域:金佛山植物1、学校植物2、藏区植物3")
const area = ref('1') // 1

onMounted(async () => {
  await getOptionList()
  id.value = route.query.id
  area.value = route.query.area as string
  if (id.value) await getPlantMedicinalDetail(Number(id.value as string))
})

const optionTotal = ref<any>()
const getOptionList = async () => {
  const res = await fetchOptionList()
  optionTotal.value = res.data.data
}

const getPlantMedicinalDetail = async (id: number) => {
  const res = await fetchPlantDetail(id)
  const detail = res.data.data
  //  'types_of_military_applications' 'geographical'
  const arrKey = ['identify_key_words', 'medicinal_parts', 'traditional_efficacy_class', 'effect', 'military_medical_class', 'disease_name_class']
  const imgKey = ['hand_painted_url', 'living_url', 'whole_plant_url', 'root_url', 'stem_url', 'leaf_url', 'flower_url', 'fruit_url', 'seed_url']
  Object.keys(formState.value).forEach(key => {
    if (arrKey.includes(key)) {
      formState.value[key] = detail[key].split(',')
    } else if(imgKey.includes(key)) {
      const imgList = detail[key] ? detail[key].split(',') : []
      formState.value[key] = imgList.map((item: string) => ({
        uid: item,
        name: item,
        status: 'done',
        url: item
      }))
    } else {
      formState.value[key] = detail[key]
    }
  })
}

const activeKey = ref('1')
const formRef = ref()
const formState = ref<any>({
  id: undefined,
  number: undefined,
  chinese_name: undefined,
  latin_name: undefined,
  alias: undefined,
  describe_info: undefined,
  identify_key_words: undefined,
  flowering_and_fruiting: undefined,
  geographical: undefined,
  medicinal_name: undefined,
  living_environment: undefined,
  medicinal_parts: undefined,
  traditional_efficacy_class: undefined,
  effect: undefined,
  military_medical_class: undefined,
  disease_name_class: undefined,
  indication_usage: undefined,
  types_of_military_applications: undefined,
  other: undefined,
  hand_painted_url: [],
  living_url: [],
  whole_plant_url: [],
  root_url: [],
  stem_url: [],
  leaf_url: [],
  flower_url: [],
  fruit_url: [],
  seed_url: []
})

const addOther = () => {
  formState.value.medicinal_field_list.push({ field_name: '', field_content: '' })
}

const delOther = (index: number) => {
  formState.value.medicinal_field_list.splice(index, 1)
}

const nextStep = () => {
  formRef.value.validate().then(async () => {
    activeKey.value = '2'
  })
}

// 处理编辑和新增时的upload组件格式不一致问题, 返回id的数组
const handleUrl = (urls: any[]) => {
  if (urls && urls.length) {
    return urls.map((item: any) => {
      if (item.response) return item.response.data.id
      return item.url.split('imageid=')[1]
    })
  }
  return []
}

const save = async () => {
  // try {
  //   await formRef.value.validate()
  // } catch {
  //   // 校验第一步是否填写完整，不完整则跳回第一步
  //   activeKey.value = '1'
  //   return
  // }
  const params = {
    ...formState.value,
    area: area.value,
    identify_key_words: formState.value.identify_key_words.toString(),
    // geographical: formState.value.geographical.toString(),
    medicinal_parts: formState.value.medicinal_parts.toString(),
    traditional_efficacy_class: formState.value.traditional_efficacy_class.toString(),
    effect: formState.value.effect.toString(),
    military_medical_class: formState.value.military_medical_class.toString(),
    disease_name_class: formState.value.disease_name_class.toString(),
    // types_of_military_applications: formState.value.types_of_military_applications.toString(),
    hand_painted_url: handleUrl(formState.value.hand_painted_url).toString(),
    living_url: handleUrl(formState.value.living_url).toString(),
    whole_plant_url: handleUrl(formState.value.whole_plant_url).toString(),
    root_url: handleUrl(formState.value.root_url).toString(),
    stem_url: handleUrl(formState.value.stem_url).toString(),
    leaf_url: handleUrl(formState.value.leaf_url).toString(),
    flower_url: handleUrl(formState.value.flower_url).toString(),
    fruit_url: handleUrl(formState.value.fruit_url).toString(),
    seed_url: handleUrl(formState.value.seed_url).toString()
  }
  const res = formState.value.id ? await fetchPlantUpdate(params) : await fetchPlantInsertOne(params)
  if (res.data.code == 200) {
    message.success('保存成功')
    router.back()
  } else message.error('保存失败，请重试')
}

// 图片相关
const actionUrl = `${import.meta.env.VITE_BASE_URL}/plant/image/upload`

function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')

const fileList = ref<any[]>([])

const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}
const handlePreview = async (file: any[number]) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}

</script>
<style lang="scss" scoped>
.plant-add {
  background-color: #fff;
}
.upload-line {
  display: flex;
  justify-content: space-between;
  margin-top: 16px;

  :deep(.ant-card) {
    width: calc(50% - 8px);
  }
}
</style>